﻿using System.Collections.Generic;
using System.Linq;
using SlamCms.Data.Internal;

namespace SlamCms.Data
{
	internal static class DatabaseExtensions
	{
		public static Dictionary<string, TagPopularity> RetrieveTagPopularities(this Database database, int tagPopularityDays)
		{
			var sql = @"select TagId, count(*) Popularity
						from TrackTagHit with (nolock)
						where Date between dateadd(day, @tagPopularityDays, getutcdate()) and getutcdate()
						group by TagId";

			return database.Query<TagPopularity>(sql, new { tagPopularityDays = tagPopularityDays * -1 }).ToDictionary(t => t.TagId);
		}

		public static Sitemap GetSitemap(this Database database, string sitemapId)
		{
			var sql = @"select * from [dbo].[Sitemap] with (nolock) where SitemapId = @sitemapId";
			var sitemap = database.Query<Sitemap>(sql, new { sitemapId })
										.FirstOrDefault();

			if (sitemap == null)
				return null;

			sql = @"select * from [dbo].[SitemapNode] with (nolock) where SitemapId = @sitemapId";
			var sitemapNodes = database.Query<SitemapNode>(sql, new { sitemapId });

			sitemap.Nodes = sitemapNodes.ToList();

			return sitemap;
		}
	}
}
